package com.bruce.tool.search.solr.domain;

import com.bruce.tool.common.exception.BaseRuntimeException;
import com.bruce.tool.common.util.string.StringUtils;
import com.bruce.tool.search.solr.exception.SearchErrorCode;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.*;

/**
 * 功能 :
 * solr查询标准参数
 * @author : Bruce(刘正航) 上午2:00 2018/5/8
 */
@NoArgsConstructor(staticName = "build")
public class FilterQuery implements Serializable {

    public static final Integer FORWARD = 1;
    public static final Integer REVERSE = -1;

    private String key;
    /**查询类型:1(正向查询),-1(排除)**/
    private Integer type = FORWARD;
    private Set<Object> values = new HashSet<>();

    public FilterQuery type(Integer type){
        this.type = type;
        return this;
    }
    /**有多个值的条件**/
    public FilterQuery addAll(String key,Integer type,Collection<?> values){
        if( StringUtils.isBlank(key) ){
            throw new BaseRuntimeException(SearchErrorCode.QUERY_KEY_NON.getCode(),SearchErrorCode.QUERY_KEY_NON.getMessage());
        }
        this.key = key;
        this.type = type;
        this.values.addAll(values);
        return this;
    }

    /**通过tostring,生成查询条件**/
    public String toString(){

        String prefix = "";
        String seperator = " or ";
        if( REVERSE.equals(type) ){
            prefix = "-";
            seperator = " and ";
        }

        List<String> list = new ArrayList<>();
        if( values.size() == 1 && StringUtils.isBlank(prefix)
                && FacetQuerys.isEnableExclude(key) ){
            String query = prefix + key + ":" + values.iterator().next();
            list.add("{!tag=" + key + "}" + query);
        }else{
            for ( Object value : values ) {
                list.add(prefix + key + ":" + value);
            }
        }

        return StringUtils.join(list,seperator);
    }
}
